import base64
import logging

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.decorators import api_view


# Create your views here.
#产生token
import random,string
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta

from rest_framework.parsers import JSONParser

from lianxi.models import userInfo, playRecord


def createtoken(name):
    #产生一个8为随机字符串
    randomstr = ''.join(random.choices(string.ascii_letters,k=8))
    #对字符串进行签名
    token=Signer().sign(randomstr+name)
    #把token保存到缓存中
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token

#校验token
def checktoken(request):
    #获取前端传过来的token
    reqtoken = request.META.get('HTTP_TOKEN')
    logging.info(f'查看前端传过来的token值:{reqtoken}')
    #如果前端没有传token，返回Falase
    if reqtoken is None:
        return False,'XXXX'
    #先做一个反签名
    untoken = Signer().unsign(reqtoken)
    logging.info(f'查看反签名的token内容{untoken}')
    name = untoken[8:]
    #检验缓存中token，存在不
    cachetoken = cache.get(f'test_{name}')
    logging.info(f'查看缓存中的token内容{cachetoken}')
    #判断缓存中token是否有效
    if cachetoken is None:
        return False,'XXXX'
    return True,name

#判空
def is_empty(c):
    return c is None or str(c).strip() == ''
#登录
@api_view(['POST'])
def denglu(request):
    body = request.data
    username = body.get('username')
    password = body.get('password')
    #判空
    if is_empty(username) or is_empty(password):
        return JsonResponse({"msg":"用户名或密码不能为空"},status=409)
    #取表值
    if userInfo.objects.filter(username=username).exists() is False:
        return JsonResponse({"msg":"用户不存在"},status=400)
    user = userInfo.objects.get(username=username)

    if user.password != password:
        return JsonResponse({"msg":"密码错误"},status=400)

    #对用户名进行加密
    bname = bytes(username,encoding='utf-8')
    # b64encode编码  decode解码
    b64name = base64.b64encode(bname).decode('utf-8')
    #把加密后的用户名传入token里
    token = createtoken(b64name)
    #返回
    return JsonResponse({"code":200,"msg":"登录成功","token":token})

#查询
@api_view(['GET'])
def getplayseleng(request):

    #校验
    falg,name = checktoken(request)
    if falg is False:
        return JsonResponse({"code":401,"msg":"未登录，请先登录"})

    page = request.GET.get('page')
    pagesize = request.GET.get('pagesize')
    #查询出所有数据对象
    allobj = playRecord.objects.filter()
    #分页
    pageobj = Paginator(allobj,pagesize)
    try:
        singlepageobj = pageobj.page(page)
    except EmptyPage:
        #数量
        singlepageobj = pageobj.page(pageobj.num_pages)
    except PageNotAnInteger:
        singlepageobj = pageobj.page(1)
    #定义一个空列表用于存数
    lis = []
    #循环singlepageobj
    for i in singlepageobj.object_list:
        lis.append({
            'id':i.id,
            'title':i.track_id.title, #获取track表里的title
            'username':i.user_id.username,
            'play_times':i.play_times,
            'play_date':i.play_date,
        })
    #allobj.count()所有的条数
    return JsonResponse({"data":lis,"code":200,"items":allobj.count()})

#播放
@api_view(['POST'])
def play(request):

    flag,name = checktoken(request)
    if flag is None:
        return JsonResponse({"code": 401, "msg": "未登录，请先登录"})

    #解析JSONParser数据
    data = JSONParser().parse(request)
    user_id = data.get('user_id')
    track_id = data.get('track_id')

    if is_empty(user_id) or is_empty(track_id):
        return JsonResponse({"code":409,"msg":"参数不能为空"})

    playRecord(track_id_id=track_id,user_id_id=user_id).save()

    return JsonResponse({"code":200,"msg":"播放成功"})
